﻿/**
* @description  Slide that displays a loaded image centered in the show.
*/
package com.foed.applications.slideshow.slides {

	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	import com.foed.applications.slideshow.SlideProperties;
	import com.foed.applications.slideshow.SlideShow;

	public class ImageSlide extends Slide {

		static public var sProperties:SlideProperties;
	
		static protected const DIRECTORY_ATTRIBUTE:String = "imageDirectory";
		static protected const FILE_ATTRIBUTE:String = "file";
	
		private var _image:Loader;
	
		/**
		* @description  Constructor.
		*
		* @param  pSlideData  The XML defining a slide instance.
		* @param  pSlideShow  The main slide show application.
		*/
		public function ImageSlide(pSlideData:XML, pSlideShow:SlideShow) {
			super(pSlideData, pSlideShow);
		}
	
		/**
		* @description  Event handler for when there is an error loading the image.
		*
		* @param  pEvent  Event fired by LoaderInfo.
		*/
		private function onLoadError(pEvent:IOErrorEvent):void {
			_image.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
			_image.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			trace("error loading image");			
		}

		/**
		* @description  Event handler for when the image completes loading.
		*
		* @param  pEvent  Event fired by LoaderInfo.
		*/
		private function onLoadComplete(pEvent:Event):void {
			_image.contentLoaderInfo.removeEventListener(Event.COMPLETE, onLoadComplete);
			_image.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			_image.x = (_slideShow.properties.width - _image.width)/2;
			_image.y = (_slideShow.properties.height - _image.height)/2;
			_content.addChild(_image);
			super.reveal();
		}
	
		/**
		* @description  Triggers a slide to reveal itself, using its appropriate transition.
		*/
		override public function reveal():void {
			_image = new Loader();
			_image.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
			_image.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
			try {
				var pDirectory:String = getAttribute(DIRECTORY_ATTRIBUTE);
				var pFile:String = pDirectory + getAttribute(FILE_ATTRIBUTE);
				_image.load(new URLRequest(pFile));
			} catch (e:Error) {
				trace(e.getStackTrace());	
			}
		}
	
	}

}